import { ReactElement, useRef } from 'react'
import { Modal, Form, FormInstance, message, Select, InputNumber } from 'antd'
import { createCaseRequest } from './ajax'
import { awaitWrap } from '@js/tool'
import { History } from 'history'
import { useNavigate, NavigateFunction } from 'react-router-dom'
import moment from 'moment'
const { Item } = Form
const { Option } = Select

// 创建案件
async function createHandle (n: NavigateFunction, data: { accept_year: number, case_no: number}): Promise<void> {
  const hide = message.loading('提交中', 120)
  const [e, d] = await awaitWrap(createCaseRequest(data))
  hide()
  if (e === null && typeof d === 'string') {
    n(`/admin/case-input/${d}`)
  }
}

interface Props {
  visible: boolean
  hide: () => void
  refreshData: () => void
}

function Main ({ visible, hide, refreshData }: Props): ReactElement {
  const n = useNavigate()
  const formRef = useRef<FormInstance>(null)
  const years = []
  const currentYear = moment().year()
  for (let i = currentYear; i >= 1996; i--) {
    years.push(i)
  }
  return (
    <Modal visible={visible} title='新建案件' onCancel={() => hide()} onOk={() => formRef.current?.submit()} maskClosable={false} destroyOnClose>
      <Form ref={formRef} labelCol={{ flex: '88px' }} onFinish={async d => await createHandle(n, d)}>
        <Item name='accept_year' label='年份' rules={[{ required: true, message: '年份不能为空' }]}>
          <Select placeholder='请选择年份'>
            {years.map(li => <Option key={li} value={li}>{li}</Option>)}
          </Select>
        </Item>
        <Item name='case_no' label='案号' rules={[{ required: true, message: '案号不能为空' }]}>
          <InputNumber placeholder='请输入案号' min={0} style={{ width: '100%' }} />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
